//
//  UIColor+AWColor.m
//  Pods
//
//  Created by TryHone on 17/9/6.
//
//

#import "UIColor+AWColor.h"
@implementation JFColorModel

@end
@implementation UIColor (AWColor)
// 颜色转换：iOS中（以#开头）十六进制的颜色转换为UIColor(RGB)
+ (UIColor *) awColorWithHexString: (NSString *)color{
    return [UIColor awColorWithHexString:color withAlpha:1.0f];
}

+ (UIColor *) ColorWithHexString: (NSString *)color{
    return [UIColor awColorWithHexString:color withAlpha:1.0f];
}
+ (UIColor *) colorWithHexString: (NSString *)color{
    return [UIColor awColorWithHexString:color withAlpha:1.0f];
}

+ (UIColor *) awColorWithHexString: (NSString *)color withAlpha:(CGFloat)alpha{
    JFColorModel * model = [UIColor awRGBWithHexString:color withAlpha:alpha];
    return [UIColor colorWithRed:((float) model.R / 255.0f) green:((float) model.G / 255.0f) blue:((float) model.B / 255.0f) alpha:alpha];
}

+ (JFColorModel *) awRGBWithHexString: (NSString *)color withAlpha:(CGFloat)alpha{
    NSString *cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    
    // String should be 6 or 8 characters
    if ([cString length] < 6) {
        return Nil;
    }
    
    // strip 0X if it appears
    if ([cString hasPrefix:@"0X"])
        cString = [cString substringFromIndex:2];
    if ([cString hasPrefix:@"#"])
        cString = [cString substringFromIndex:1];
    if ([cString length] != 6)
        return Nil;
    
    // Separate into r, g, b substrings
    NSRange range;
    range.location = 0;
    range.length = 2;
    
    //r
    NSString *rString = [cString substringWithRange:range];
    
    //g
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    
    //b
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    
    // Scan values
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    
    JFColorModel *rgb = [[JFColorModel alloc] init];
    rgb.R = r;
    rgb.B = b;
    rgb.G = g;
    rgb.alpha = alpha;
    return  rgb;
}
- (NSString *)awHexString{
    NSString *webColor = nil;
    if (CGColorGetNumberOfComponents(self.CGColor) == 4)
    {
        const CGFloat *components = CGColorGetComponents(self.CGColor);
        CGFloat red = roundf(components[0] * 255.0);
        CGFloat green = roundf(components[1] * 255.0);
        CGFloat blue = roundf(components[2] * 255.0);
        webColor = [NSString stringWithFormat:@"%02lx%02lx%02lx", (long)red, (long)green, (long)blue];
    }
    return webColor;
}
+ (UIColor*)awRandomColor{
    return [UIColor colorWithRed:arc4random_uniform(256)/255.0 green:arc4random_uniform(256)/255.0 blue:arc4random_uniform(256)/255.0 alpha:1.0];
}


@end
